<script setup lang="ts">
import ToolView from "@/modules/tools/layout/tool-view.vue";
import { computed, ref } from "vue";
import InputCopyable from "@/components/framework/input-copyable.vue";
import ScrollView from "@/components/framework/scroll-view.vue";

const inputUrl = ref("https://root:pwd@gitee.com:443/suihan-y?key1=value&key2=value2#the-hash");

const properties: { title: string; key: keyof URL }[] = [
  { title: "Protocol", key: "protocol" },
  { title: "Username", key: "username" },
  { title: "Password", key: "password" },
  { title: "Hostname", key: "hostname" },
  { title: "Port", key: "port" },
  { title: "Path", key: "pathname" },
  { title: "Hash", key: "hash" },
  { title: "Params", key: "search" },
];

const result = computed(() => {
  try {
    return { ok: true, url: new URL(inputUrl.value) };
  } catch (e: any) {
    return { ok: false, error: e.message };
  }
});
</script>

<template>
  <tool-view title="URL解析器" description="解析url字符串以获取所有不同的部分（协议、来源、参数、端口、用户名密码…）">
    <div class="pv-20 full-view flex jcc">
      <scroll-view>
        <div class="w-80p" style="margin: 0 auto">
          <div class="mb-10">输入你要解析的URL：</div>
          <a-input v-model:value="inputUrl" :status="result.ok ? undefined : 'error'" size="large" allow-clear />

          <div class="mt-20">
            <template v-for="it in properties" :key="it.key">
              <div class="mb-10 flex aic">
                <span class="w-130">{{ it.title }}</span>
                <div class="flex-1">
                  <input-copyable :value="result.url?.[it.key]" readonly />
                </div>
              </div>
            </template>
          </div>
          <div class="mt-20" style="padding-left: 130px">
            <template v-for="[k, v] in Object.entries(Object.fromEntries(result.url?.searchParams.entries() ?? []))">
              <div class="mb-10 flex col-gap-10 child-flex-1">
                <div>
                  <input-copyable :value="k" readonly />
                </div>
                <div>
                  <input-copyable :value="v" readonly />
                </div>
              </div>
            </template>
          </div>
        </div>
      </scroll-view>
    </div>
  </tool-view>
</template>

<style scoped lang="less"></style>
